﻿using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Letter.Net.Kcp;

class KcpClient : AKcpHost, IKcpClient
{
    public KcpClient(string name) : base(name)
    {
    }

    public override EndPoint BindEndPoint { get; }

    private EndPoint remote;
    
    protected override AConnection ConfigureConnection()
    {
        return new CUdpConnection(this.remote, this.transportOptions, CreateConnection, this.channelProvider);
    }
    
    public override async Task ConnectAsync(EndPoint endPoint)
    {
        if (this.host == null)
        {
            return;
        }

        this.remote = endPoint;
        
        if (this.remote.AddressFamily == AddressFamily.InterNetworkV6)
        {
            await host.BindAsync(new IPEndPoint(IPAddress.IPv6Any, 0));
        }
        else if(this.remote.AddressFamily == AddressFamily.InterNetwork)
        {
            await host.BindAsync(new IPEndPoint(IPAddress.Any, 0));
        }
    }

    public override Task StopAsync()
    {
        return this.host.StopAsync();
    }
}